<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\model;

use think\Db;
use think\Model;
use think\Request;

class UserModel extends Model
{
    protected $type = [
        'more' => 'array',
    ];

    public function doMobile($user)
    {
        $result = $this->where('mobile', $user['mobile'])->find();


        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam = [
                'user' => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {
                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                session('user', $result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_client_ip(0, true),
                ];
                $this->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user' => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function doName($user)
    {
        $result = $this->where('user_login', $user['user_login'])->find();
        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam = [
                'user' => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {
                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                session('user', $result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_client_ip(0, true),
                ];
                $result->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user' => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function doEmail($user)
    {

        $result = $this->where('user_email', $user['user_email'])->find();

        if (!empty($result)) {
            $comparePasswordResult = cmf_compare_password($user['user_pass'], $result['user_pass']);
            $hookParam = [
                'user' => $user,
                'compare_password_result' => $comparePasswordResult
            ];
            hook_one("user_login_start", $hookParam);
            if ($comparePasswordResult) {

                //拉黑判断。
                if ($result['user_status'] == 0) {
                    return 3;
                }
                session('user', $result->toArray());
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_client_ip(0, true),
                ];
                $this->where('id', $result["id"])->update($data);
                $token = cmf_generate_user_token($result["id"], 'web');
                if (!empty($token)) {
                    session('token', $token);
                }
                return 0;
            }
            return 1;
        }
        $hookParam = [
            'user' => $user,
            'compare_password_result' => false
        ];
        hook_one("user_login_start", $hookParam);
        return 2;
    }

    public function register($user, $type)
    {
        switch ($type) {
            case 1:
                $result = Db::name("user")->where('user_login', $user['user_login'])->find();
                break;
            case 2:
                $result = Db::name("user")->where('mobile', $user['mobile'])->find();
                break;
            case 3:
                $result = Db::name("user")->where('user_email', $user['user_email'])->find();
                break;
            default:
                $result = 0;
        }

        $userStatus = 1;

        if (cmf_is_open_registration()) {
            $userStatus = 2;
        }

        if (empty($result)) {
            $data = [
                'user_login' => empty($user['user_login']) ? $this->randUserLogin() : $user['user_login'],
                'user_email' => empty($user['user_email']) ? '' : $user['user_email'],
                'mobile' => empty($user['mobile']) ? '' : $user['mobile'],
                'user_nickname' => '',
                'user_pass' => cmf_password($user['user_pass']),
                'last_login_ip' => get_client_ip(0, true),
                'create_time' => time(),
                'last_login_time' => time(),
                'user_status' => $userStatus,
                "user_type" => 2,//会员
            ];
            $userId = Db::name("user")->insertGetId($data);
            $data = Db::name("user")->where('id', $userId)->find();
            cmf_update_current_user($data);
            $token = cmf_generate_user_token($userId, 'web');
            $name = empty($data['user_nickname'])?$data['user_login']:$data['user_nickname'];
            $ret = $this->collect_invite($userId,$name);
            if($ret){
                $this->share_out($userId);
            }else{ return 0;}

            if (!empty($token)) {
                session('token', $token);
            }
            return 0;
        }
        return 1;
    }

    /**
     * 通过邮箱重置密码
     * @param $email
     * @param $password
     * @return int
     */
    public function emailPasswordReset($email, $password)
    {
        $result = $this->where('user_email', $email)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $this->where('user_email', $email)->update($data);
            return 0;
        }
        return 1;
    }

    /**
     * 通过手机重置密码
     * @param $mobile
     * @param $password
     * @return int
     */
    public function mobilePasswordReset($mobile, $password)
    {
        $userQuery = Db::name("user");
        $result = $userQuery->where('mobile', $mobile)->find();
        if (!empty($result)) {
            $data = [
                'user_pass' => cmf_password($password),
            ];
            $userQuery->where('mobile', $mobile)->update($data);
            return 0;
        }
        return 1;
    }

    public function editData($user)
    {
        $userId = cmf_get_current_user_id();

        if (isset($user['birthday'])) {
            $user['birthday'] = strtotime($user['birthday']);
        }

        $field = 'user_nickname,sex,birthday,user_url,signature,more';

        if ($this->allowField($field)->save($user, ['id' => $userId])) {
            $userInfo = $this->where('id', $userId)->find();
            cmf_update_current_user($userInfo->toArray());
            return 1;
        }
        return 0;
    }

    /**
     * 用户密码修改
     * @param $user
     * @return int
     */
    public function editPassword($user)
    {
        $userId = cmf_get_current_user_id();
        $userQuery = Db::name("user");
        if ($user['password'] != $user['repassword']) {
            return 1;
        }
        $pass = $userQuery->where('id', $userId)->find();
        if (!cmf_compare_password($user['old_password'], $pass['user_pass'])) {
            return 2;
        }
        $data['user_pass'] = cmf_password($user['password']);
        $userQuery->where('id', $userId)->update($data);
        return 0;
    }

    public function comments()
    {
        $userId = cmf_get_current_user_id();
        $userQuery = Db::name("Comment");
        $where['user_id'] = $userId;
        $where['delete_time'] = 0;
        $favorites = $userQuery->where($where)->order('id desc')->paginate(10);
        $data['page'] = $favorites->render();
        $data['lists'] = $favorites->items();
        return $data;
    }

    public function deleteComment($id)
    {
        $userId = cmf_get_current_user_id();
        $userQuery = Db::name("Comment");
        $where['id'] = $id;
        $where['user_id'] = $userId;
        $data['delete_time'] = time();
        $userQuery->where($where)->update($data);
        return $data;
    }

    /**
     * 绑定用户手机号
     */
    public function bindingMobile($user)
    {
        $userId = cmf_get_current_user_id();
        $data ['mobile'] = $user['username'];
        Db::name("user")->where('id', $userId)->update($data);
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     * 绑定用户邮箱
     */
    public function bindingEmail($user)
    {
        $userId = cmf_get_current_user_id();
        $data ['user_email'] = $user['username'];
        Db::name("user")->where('id', $userId)->update($data);
        $userInfo = Db::name("user")->where('id', $userId)->find();
        cmf_update_current_user($userInfo);
        return 0;
    }

    /**
     *   @Notes: 随机个账户
     *   @Function randUserLogin
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *   @author:
     *   @Time: 2018/11/20 0020   14:39
     * xxx
     */
    public function randUserLogin($a = 0)
    {
        $a++;
        $data = array();
        $k = mt_rand(1, 7);  //随机11位数
        for ($i = 0; $i < $k; $i++) {
            array_push($data, mt_rand(0, 9));
        }
        $data = implode('', $data);
        $ret = Db::name('user')->where('user_login', $data)->find();
        if ($ret && $a < 10) {
            $this->randUserLogin($a);//如果数据库已经有了，就重新再随机一个
        } else {
            return $data;
        }

    }

    /**
     *   @Notes: 获取邀请码，如果没有就不做处理，有的话将数据写入层级关系表里面distribute
     *   @Function collect_invite
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *   @author: xy
     *   @Time: 2018/11/23 0023   11:37
     * xxx
     */
    public function collect_invite($userId,$name)
    {
        $request = Request::instance();
        $invite_key = $request->get('invite_key');
        if (empty($invite_key) || isset($invite_key)) {
            $invite_key = $request->cookie('invite_key');
        }
        //$invite_key = 1;
        if (!empty($invite_key) && !empty($userId)) {
            $ret = Db::name('distribute')->where('user_id',$invite_key)->find();
            $time = date("Y-m-d H:i:s",time());
            $data = [
                'user_id' => $userId,
                'father_id' => $invite_key,
                'grandpa_id' => empty($ret['father_id'])?'':$ret['father_id'],
                'great_grandpa_id' => empty($ret['grandpa_id'])?'':$ret['grandpa_id'],
                'create_time' => $time,
                'user_name' => empty($name)?'':$name,
                'father_name' => empty($ret['user_name'])?'':$ret['user_name'],
                'grandpa_name' => empty($ret['father_name'])?'':$ret['father_name'],
                'great_grandpa_name' => empty($ret['grandpa_name'])?'':$ret['grandpa_name'],
            ];
            $ret = Db::name('distribute')->insert($data);
            return $ret;
       }else{
            return false;
        }
    }

    /**
     *   @Notes:给新注册的用户赠送些积分，顺便给其父级们奖励下些
     *   @Function share_out
     *   @author: xy
     *   @Time: 2018/11/23 0023   13:17
     * xxx
     */
    public function share_out($user_id){
        $share_data = Db::name('share_out')->select();

        $data_user = Db::name('user')->where('id',$user_id)->find();
        if($data_user){
            $data = $data_user['score'] + 100;
            Db::name('user')->where('id', $user_id)->update(['score' => $data]);
        }

        $data_out = Db::name('distribute')->where('user_id',$user_id)->find();
        if($data_out){
            $data_father =  Db::name('user')->where('id',$data_out['father_id'])->find();
            $data_grandpa =  Db::name('user')->where('id',$data_out['grandpa_id'])->find();
            $data_great_grandpa =  Db::name('user')->where('id',$data_out['great_grandpa_id'])->find();
            /* 父级奖励*/
            if($data_father){
                $var = 100*$share_data[1]['share_out_num']/100;
                $data_father = $data_father['score']+$var;
                $father_contribute = $data_out['father_contribute']+$var;
                Db::name('user')->where('id', $data_out['father_id'])->update(['score' => $data_father]);
                Db::name('distribute')->where('id', $data_out['id'])->update(['father_contribute' => $father_contribute]);
                $data =[
                    'user_id' =>$data_out['father_id'],
                    'create_time' =>time(),
                    'change_score' => $var,
                    'score' => $data_father,
                    'remark' => '新用户:'.$data_user['user_login'].'注册奖励积分-1级',
                ];
                Db::name('user_balance_log')->insert($data);
            }
            /* 祖级奖励*/
            if($data_grandpa){
                $var = 100*$share_data[2]['share_out_num']/100;
                $data_grandpa =  $data_grandpa['score']+$var;
                $grandpa_contribute = $data_out['grandpa_contribute']+$var;
                Db::name('distribute')->where('id', $data_out['id'])->update(['grandpa_contribute' => $grandpa_contribute]);
                Db::name('user')->where('id', $data_out['grandpa_id'])->update(['score' => $data_grandpa]);
                $data =[
                    'user_id' =>$data_out['grandpa_id'],
                    'create_time' =>time(),
                    'change_score' => $var,
                    'score' => $data_grandpa,
                    'remark' => '新用户:'.$data_user['user_login'].'注册奖励积分-2级',
                ];
                Db::name('user_balance_log')->insert($data);
            }
            /* 太级奖励*/
            if($data_great_grandpa){
                $var = 100*$share_data[3]['share_out_num']/100;
                $data_great_grandpa = $data_great_grandpa['score']+ $var;
                $great_grandpa_contribute = $data_out['great_grandpa_contribute']+$var;
                Db::name('distribute')->where('id', $data_out['id'])->update(['great_grandpa_contribute' => $great_grandpa_contribute]);
                Db::name('user')->where('id', $data_out['great_grandpa_id'])->update(['score' => $data_great_grandpa]);
                $data =[
                    'user_id' =>$data_out['great_grandpa_id'],
                    'create_time' =>time(),
                    'change_score' => $var,
                    'score' => $data_great_grandpa,
                    'remark' => '新用户:'.$data_user['user_login'].'注册奖励积分-3级',
                ];
                Db::name('user_balance_log')->insert($data);
            }
        }
    }
}
